package com.gandong8.trace.tool.service.impl;

import com.gandong8.trace.tool.core.SystemClock;
import com.gandong8.trace.tool.domain.ResponseData;
import com.gandong8.trace.tool.util.JsonUtil;
import com.gandong8.trace.tool.util.RetryUtil;
import com.gandong8.trace.tool.domain.RequestData;
import com.gandong8.trace.tool.service.HttpService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
abstract class HttpPublicService implements HttpService {
    @Override
    public <T> T go(RequestData requestData, Class<T> responseClass) {
        int retry = requestData.getRetryNum();
        try {
            if(retry > 0) {
                return RetryUtil.run(() -> request(requestData, responseClass), retry, requestData.getRetryTime());
            } else {
                return request(requestData, responseClass);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public <T> T go(RequestData requestData) {
        return go(requestData, null);
    }

    @SuppressWarnings("unchecked")
    private  <T> T request(RequestData requestData, Class<T> responseClass) throws Exception {
        log.info("http_begin:" + requestData.toString());
        long startTime = SystemClock.now();
        ResponseData responseData = doBoth(requestData);
        responseData.setCostTime(SystemClock.now() - startTime);
        log.info("http_end:" + responseData.toString());
        return responseClass == null ? (T) responseData.getData() : JsonUtil.toObj(responseData.getData(), responseClass);
    }
    abstract ResponseData doBoth(RequestData requestData) throws Exception ;
}
